package com.xuzz.study.thread.lock;

public class ReentrantLock {
    private boolean isLocked = false;
    Thread lockedBy = null;
    int lockedCount = 0 ;
    public synchronized void lock()
            throws InterruptedException
    {
        Thread callThread = Thread.currentThread();
        while(isLocked && lockedBy!=callThread)
        {
            wait();
        }
        isLocked=true;
        lockedCount++;
        lockedBy = callThread;
    }

    public synchronized void unlock()
            throws InterruptedException
    {
        Thread callThread = Thread.currentThread();
        if(lockedBy == callThread)
        {
            lockedCount--;
            if(lockedCount==0)
            {
                isLocked=false;
                lockedBy=null;
                notifyAll();
            }
        }
    }
}
